package com.macro.mall.wms.service.impl;

import com.github.pagehelper.PageHelper;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.mapper.*;
import com.macro.mall.model.*;
import com.macro.mall.wms.dto.InStorageDto;
import com.macro.mall.wms.dto.WmsInStorageItemDTO;
import com.macro.mall.wms.service.IInStorageService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class InStorageServiceImpl implements IInStorageService {
    @Autowired
    private WmsInStorageMapper inStorageMapper;
    @Autowired
    private WmsInStorageItemMapper inStorageItemMapper;
    @Autowired
    private PmsStockMapper stockMapper;
    @Autowired
    private PmsSkuStockMapper skuStockMapper;
    @Autowired
    private PmsProductMapper productMapper;

    @Override
    public CommonResult createInStorage(Long adminId, String username, Long storeId, InStorageDto inStorageDto) {
        WmsInStorage wmsInStorage = new WmsInStorage();
        wmsInStorage.setCreatTime(new Date());
        wmsInStorage.setMemberId(adminId);
        wmsInStorage.setMemberUserName(username);
        wmsInStorage.setStoreId(storeId);
        wmsInStorage.setStatus(0);
        wmsInStorage.setNote(inStorageDto.getNote());
        //获取入库单号并set
        wmsInStorage.setInStorageSn(getInStorageSn());

        List<WmsInStorageItem> list = inStorageDto.getSeckill_arr();
        if (CollectionUtils.isEmpty(list)) {
            return CommonResult.failed("请选择入库商品");
        }
        inStorageMapper.insertSelective(wmsInStorage);
        //把子出库单数据修改后放入待新增集合中
        for (WmsInStorageItem inStorageItem : list) {
            inStorageItem.setInStorageId(wmsInStorage.getId());
            inStorageItem.setMemberId(adminId);
            inStorageItem.setMemberUserName(username);
            inStorageItem.setStoreId(storeId);
            inStorageItemMapper.insertSelective(inStorageItem);
        }
        return CommonResult.success("入库成功，请及时审核");
    }

    @Override
    public CommonResult cudInStorage(Long adminId, String username, Long storeId, Long id, InStorageDto inStorageDto) {
        List<WmsInStorageItem> list = inStorageDto.getSeckill_arr();
        WmsInStorage wmsInStorage = inStorageMapper.selectByPrimaryKey(id);
        if (!StringUtils.isEmpty(inStorageDto.getNote())) {
            wmsInStorage.setNote(inStorageDto.getNote());
            inStorageMapper.updateByPrimaryKeySelective(wmsInStorage);
        }
        if (CollectionUtils.isEmpty(list)) {
            return CommonResult.failed("参数为空");
        }
        //待新增商品
        List<WmsInStorageItem> insertList = list.stream().filter(e -> e.getId() == null).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(insertList)) {
            for (WmsInStorageItem inStorageItem : insertList) {
                inStorageItem.setInStorageId(wmsInStorage.getId());
                inStorageItem.setMemberId(adminId);
                inStorageItem.setMemberUserName(username);
                inStorageItem.setStoreId(storeId);
                inStorageItemMapper.insertSelective(inStorageItem);
            }
        }
        //待修改商品
        List<WmsInStorageItem> updateList = list.stream().filter(e -> e.getId() != null).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(updateList)) {
            for (WmsInStorageItem inStorageItem : updateList) {
                if (adminId.equals(inStorageItem.getMemberId())) {
                    inStorageItemMapper.updateByPrimaryKeySelective(inStorageItem);
                }
            }
        }
        //待删除商品
        List<Long> updateSkuIds = list.stream().map(WmsInStorageItem::getId).collect(Collectors.toList());
        List<WmsInStorageItem> removeSkuList = list.stream().filter(item -> !updateSkuIds.contains(item.getId())).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(removeSkuList)) {
            List<Long> removeSkuIds = removeSkuList.stream().map(WmsInStorageItem::getId).collect(Collectors.toList());
            WmsInStorageItemExample removeExample = new WmsInStorageItemExample();
            removeExample.createCriteria().andIdIn(removeSkuIds);
            inStorageItemMapper.deleteByExample(removeExample);
        }
        return CommonResult.success("成功");
    }

    @Override
    public CommonResult auditInStorage(Long adminId, String username, Long storeId, Long id) {
        int insert = 0;
        int update = 0;
        WmsInStorage wmsInStorage = inStorageMapper.selectByPrimaryKey(id);
        if (!adminId.equals(wmsInStorage.getMemberId())) {
            return CommonResult.failed("不能审核不是自己的入库单");
        }
        //更改入库单审核状态
        wmsInStorage.setStatus(1);
        //记录完成时间
        wmsInStorage.setFinishTime(new Date());
        WmsInStorageItemExample example = new WmsInStorageItemExample();
        example.createCriteria().andInStorageIdEqualTo(wmsInStorage.getId());
        List<WmsInStorageItem> items = inStorageItemMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(items)) {
            return CommonResult.failed("该入库单下没有商品");
        }
        for (WmsInStorageItem item : items) {
            //判断pms_stock中存在不存在该商品
            PmsStockExample pmsStockExample = new PmsStockExample();
            pmsStockExample.createCriteria().andSkuStockIdEqualTo(item.getSkuStockId()).andAgentIdIsNull();
            List<PmsStock> pmsStocks = stockMapper.selectByExample(pmsStockExample);
            if (CollectionUtils.isEmpty(pmsStocks)) {
                //不存在，为新商品，添加库存
                PmsStock pmsStock = new PmsStock();
                pmsStock.setStock(item.getQuantity());
                pmsStock.setSkuStockId(item.getSkuStockId());
                pmsStock.setMemberId(adminId);
                pmsStock.setMemberUserName(username);
                pmsStock.setStoreId(storeId);
                insert = stockMapper.insertSelective(pmsStock);
            } else {
                //存在，为已有商品，修改库存
                PmsStock pmsStock = pmsStocks.get(0);
                //原有数量+入库数量
                int stock = pmsStock.getStock() + item.getQuantity();
                pmsStock.setStock(stock);
                update = stockMapper.updateByPrimaryKey(pmsStock);
            }
            //总库存加数量
            PmsSkuStock pmsSkuStock = skuStockMapper.selectByPrimaryKey(item.getSkuStockId());
            Integer stock = pmsSkuStock.getStock();
            Integer quantity = item.getQuantity();
            //修改总数量
            pmsSkuStock.setStock(stock + quantity);
            skuStockMapper.updateByPrimaryKeySelective(pmsSkuStock);
        }
        //修改入库单状态
        inStorageMapper.updateByPrimaryKeySelective(wmsInStorage);
        if (insert > 0 || update > 0) {
            return CommonResult.success("审核成功");
        } else {
            return CommonResult.failed("审核失败");
        }
    }

    @Override
    public CommonResult deleteInStorage(Long id, Long adminId) {
        WmsInStorage wmsInStorage = inStorageMapper.selectByPrimaryKey(id);
        if (!adminId.equals(wmsInStorage.getMemberId())) {
            return CommonResult.failed("不能删除不是自己的入库单");
        }
        if (wmsInStorage.getStatus() == 1L) {
            return CommonResult.failed("不能删除已审核的入库单");
        }
        WmsInStorageItemExample example = new WmsInStorageItemExample();
        example.createCriteria().andInStorageIdEqualTo(wmsInStorage.getId());
        List<WmsInStorageItem> items = inStorageItemMapper.selectByExample(example);
        //待删除的入库单下的商品
        List<Long> removeIds = items.stream().map(WmsInStorageItem::getId).collect(Collectors.toList());
        example.createCriteria().andIdIn(removeIds);
        inStorageItemMapper.deleteByExample(example);
        int delete = inStorageMapper.deleteByPrimaryKey(id);
        if (delete == 1) {
            return CommonResult.success("删除入库单成功");
        } else {
            return CommonResult.failed("删除入库单失败");
        }
    }

    @Override
    public List<WmsInStorageItemDTO> getInStorageItems(Long orderId) {
        List<WmsInStorageItemDTO> list = new ArrayList<>();
        WmsInStorageItemExample example = new WmsInStorageItemExample();
        example.createCriteria().andInStorageIdEqualTo(orderId);
        List<WmsInStorageItem> items = inStorageItemMapper.selectByExample(example);
        Map<Long, PmsProduct> productMap = new HashMap<>();
        for (WmsInStorageItem item : items) {
            WmsInStorageItemDTO dto = new WmsInStorageItemDTO();
            BeanUtils.copyProperties(item, dto);
            PmsProduct product = null;
            PmsSkuStock pmsSkuStock = this.skuStockMapper.selectByPrimaryKey(item.getSkuStockId());
            if (pmsSkuStock == null) {
                continue;
            }
            BeanUtils.copyProperties(pmsSkuStock, dto);
            if (productMap.get(item.getSkuStockId()) != null) {
                product = productMap.get(item.getSkuStockId());
            } else {
                product = this.productMapper.selectByPrimaryKey(pmsSkuStock.getProductId());
                productMap.put(product.getId(), product);
            }
            dto.setPic(product.getPic());
            dto.setName(product.getName());
            list.add(dto);
        }
        return list;
    }

    @Override
    public List<WmsInStorage> getInStorageList(Long storeId, WmsInStorage wmsInStorage, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        WmsInStorageExample example = new WmsInStorageExample();
        WmsInStorageExample.Criteria criteria = example.createCriteria();
        //根据入库单code和状态模糊查询
        if (wmsInStorage.getInStorageSn() != null && !"".equals(wmsInStorage.getInStorageSn())) {
            criteria.andInStorageSnLike("%" + wmsInStorage.getInStorageSn() + "%");
        }
        if (wmsInStorage.getStatus() != null) {
            criteria.andStatusEqualTo(wmsInStorage.getStatus());
        }
        criteria.andStoreIdEqualTo(storeId);
        //查询该用户所有入库单
        example.setOrderByClause("creat_time desc");
        List<WmsInStorage> wmsInStorages = inStorageMapper.selectByExample(example);
        return wmsInStorages;
    }

    @Override
    public CommonResult<InStorageDto> getInStorage(Long id) {
        WmsInStorage storage = inStorageMapper.selectByPrimaryKey(id);
        InStorageDto inStorageDto = toDTO(storage);
        return CommonResult.success(inStorageDto);
    }

    /**
     * 根据入库单返回入库单和商品的封装
     *
     * @param storage
     * @return
     */
    private InStorageDto toDTO(WmsInStorage storage) {
        InStorageDto dto = new InStorageDto();
        dto.setId(storage.getId());
        dto.setStatus(storage.getStatus());
        dto.setCreatTime(storage.getCreatTime());
        dto.setInStorageSn(storage.getInStorageSn());
        dto.setMemberId(storage.getMemberId());
        dto.setMemberUserName(storage.getMemberUserName());
        dto.setType(storage.getType());
        dto.setStoreId(storage.getStoreId());
        dto.setFinishTime(storage.getFinishTime());
        //查询该入库单下所有入库商品
        WmsInStorageItemExample itemExample = new WmsInStorageItemExample();
        itemExample.createCriteria().andInStorageIdEqualTo(storage.getId());
        List<WmsInStorageItem> items = inStorageItemMapper.selectByExample(itemExample);
        dto.setSeckill_arr(items);
        return dto;
    }

    /**
     * 获取入库单的单号
     *
     * @return
     */
    private String getInStorageSn() {
        String inStorageSn = "";
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        WmsInStorageExample example = new WmsInStorageExample();
        example.createCriteria().andInStorageSnLike(sdf.format(date) + "%");
        example.setOrderByClause("id");
        List<WmsInStorage> wmsInStorages = inStorageMapper.selectByExample(example);
        if (wmsInStorages.size() == 0) {
            //当天还没有新建入库单
            inStorageSn = sdf.format(date).substring(0, 8) + "0000";
        } else {
            String sn = wmsInStorages.get(wmsInStorages.size() - 1).getInStorageSn();
            Integer count = Integer.parseInt(sn.substring(8));
            //当天新建了countByDay条入库单，取countByDay+1作为新的编号的后缀
            inStorageSn = sdf.format(date).substring(0, 8) + String.format("%04d", count+1);
        }
        return inStorageSn;
    }

}
